﻿#include "SplitPieChart.h"
#include "nightcharts.h"
#include <numeric>

SplitPieChart::SplitPieChart(QWidget *parent) :
	QWidget(parent)
{
	clear();	
}

void SplitPieChart::clear()
{
	_chart = Nightcharts();
	_chart.setType(Nightcharts::Pie);
	_chart.setLegendType(Nightcharts::Vertical);		
}

void SplitPieChart::setResult(SplitResult result)
{
	clear();

	QVector<QColor> colorList;
	colorList << Qt::red << Qt::green << Qt::blue << Qt::yellow << Qt::cyan << Qt::magenta
		<< Qt::white << Qt::gray << Qt::darkRed << Qt::darkGreen << Qt::darkBlue
		<< Qt::lightGray << Qt::darkYellow << Qt::darkCyan << Qt::darkMagenta << Qt::darkGray;

	int color_idx = 0;	
	for (int i = 0; i < result.indexs.size(); i++)
	{
		if (result.indexs[i].size() != 0)
		{
			QString name = (i < 15) ? QString('A' + i) : tr("落选");
			_chart.addPiece(name, colorList[color_idx++], (float)result.indexs[i].size() / result.sumItem * 100);
		}
	}
	update();
}

void SplitPieChart::paintEvent(QPaintEvent * e)
{	
	QLinearGradient back_gradient(0, 0, width(), height());
	back_gradient.setColorAt(0, QColor(240, 240, 240));
	back_gradient.setColorAt(1, QColor(60, 60, 60));

	QBrush back(back_gradient);
	
	QPainter painter(this);
	painter.fillRect(rect(), back);	

	QRect text_rc = QRect(0, 20, width(), 60);
	QFont font = painter.font();
	font.setPixelSize(40);
	painter.setFont(font);

	painter.drawText(text_rc, tr("分选结果"),QTextOption(Qt::AlignCenter));
	font.setPixelSize(16);
	painter.setFont(font);
	
	int margin_left = 10;
	int margin_top = 90;
	int legend_width = 120;
	if (_chart.pieceCount() > 0)
	{
		int w = this->width() - 2 * margin_left - legend_width;
		int h = this->height() - margin_top - 10;
		int size = qMin(w, h)/1.2;
		_chart.setCords(margin_left + (w-size)/2, margin_top, size, size);

		_chart.draw(&painter);

		_chart.setLegendCords(margin_left + w, margin_top + 10);
		_chart.drawLegend(&painter);
	}
}

void SplitPieChart::addItem(QString name, QColor color, float value)
{
	_chart.addPiece(name, color, value);
}
